package com.example.wechat114.commons;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtil2 {

    /**
     *  http发送get请求
     * @param url
     * @return
     */
    public static JSONObject doGet(String url){
        //创建请求方式
        HttpGet httpGet = new HttpGet(url);
        //创建客户端
        HttpClient httpClient = new DefaultHttpClient();

        try {
            return getJsonObject(httpClient.execute(httpGet));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static JSONObject getJsonObject(HttpResponse execute) {
        try {
            //执行发送请求并得到响应结果
            HttpResponse httpResponse = execute;
            if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                return JSONObject.parseObject(EntityUtils.toString(httpResponse.getEntity(), "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  http发送post请求
     * @param url
     * @param data
     * @return
     */
    public static JSONObject doPost(String url, String data){
        //创建请求方式
        HttpPost httpPost = new HttpPost(url);
        //创建客户端
        HttpClient httpClient = new DefaultHttpClient();
        //将请求的数据放入post请求体中
        httpPost.setEntity(new StringEntity(data,"utf-8"));

        try {
            //执行发送请求并得到响应结果
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                return JSONObject.parseObject(EntityUtils.toString(httpResponse.getEntity(), "utf-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
